//
//  MainNavigationController.swift
//  BoostTestIOS
//
//  Created by 张海南 on 2023/4/17.
//

import UIKit

class MainNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()
        modalPresentationStyle = .fullScreen
        navigationBar.isTranslucent = false
        navigationBar.shadowImage = UIImage()
        setupAppearance()
    }
    
    private func setupAppearance() {
        if #available(iOS 13.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = UIColor(hexString: "#609AF6")
            // 设置取消按钮的字
            appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
            navigationBar.standardAppearance = appearance
            
            navigationBar.scrollEdgeAppearance = navigationBar.standardAppearance
            navigationBar.standardAppearance = navigationBar.standardAppearance // 常规页面。描述导航栏以标准高度
        } else {
            UINavigationBar.appearance().barTintColor = UIColor(hexString: "#609AF6")
            UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
            UINavigationBar.appearance().tintColor = .white
        }
        
        navigationBar.barTintColor = .white
        navigationBar.tintColor = .white

        //设置隐藏底部的横线
        if #available(iOS 13.0, *) {
            navigationBar.compactAppearance?.shadowImage = UIImage()
        }
    }
    
    override public func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if viewControllers.count > 0 {
            navigationBar.isHidden = false
            viewController.hidesBottomBarWhenPushed = true
            let image = UIImage(named: "icon_left_black")?.withRenderingMode(.alwaysOriginal)
            let backButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(self.backButtonDidTouchUpInside))
            viewController.navigationItem.leftBarButtonItem = backButtonItem
        }
        // 避免同一个控制器被push多次
        if viewControllers.contains(viewController) {
            return
        }
        super.pushViewController(viewController, animated: animated)
    }

    @objc func backButtonDidTouchUpInside() {
        self.popViewController(animated: true)
        self.hidesBottomBarWhenPushed = false
    }

}
